package io.xxx.xbutler.core.check;

import io.xxx.xbutler.constant.Formats;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Task;
import io.xxx.xbutler.domain.task.TaskStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Order(10)
@Component
public class TaskChecker implements Checker {

    @Override
    public CheckError check(PushContext context) {
        Task task = context.getTask();
        if (task.getStatus() == TaskStatus.CANCELED) {
            CheckError error = CheckError.TaskCancelled;
            log.info("{}[taskId:{}, taskStatus:{}]", error.getErrorMessage(), task.getId(), task.getStatus());
            return error;
        }

        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(task.getEndTime())) {
            CheckError error = CheckError.TaskExpired;
            log.info("{}[taskId:{}, endTime:{}, currentTime:{}]", error.getErrorMessage(), task.getId(), task.getEndTime().format(Formats.DATETIME_FORMATTER), now.format(Formats.DATETIME_FORMATTER));
            return error;
        }
        return null;
    }

    @Override
    public boolean supports(PushContext context) {
        return true;
    }
}
